package proxy;

import java.io.File;
import java.io.IOException;
import java.nio.ByteBuffer;

import com.Communicator;

import core.Config;
import core.Launcher;

import interfaces.*;

public class LauncherProxy extends Thread {
	
	// Canal de comunicação do procurador do lançador
	private ICommunicator launcherProxyChannel;

	// Canal de comunicação com o gerente
	private ICommunicator bossChannelSend;
	
	private String defaultIP = Config.DEFAULT_IP;
	
	// Define um lançador
	private Launcher launcher;
	
	private boolean running = true;
	
	// Identificação do trabalhador
	private String workerId;
	
	// Descrição do canal de comunicação do trabalhador
	private String channelDesc;
	
	// Tamanho da mensagem
	@SuppressWarnings("unused")
	private int size;
	
	// Tipo da mensagem
	private short msg_type;

	
	public LauncherProxy() {
		this.launcherProxyChannel = new Communicator(this.defaultIP);
		this.launcher = new Launcher(this, this.launcherProxyChannel.serverChannelDescription());
		
		System.out.println("LauncherProxy iniciado =>");
		System.out.println("\t Seu canal eh: " + this.launcherProxyChannel.serverChannelDescription() + "\n");
		
		this.start();		
		try {
			Thread.sleep(500);
			this.launcher.Initialize(new File(Config.NODES_DESC));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		try {
			this.launcher.launchNodes();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void run() {
		try {
			ByteBuffer buf = null;
			/////////////////////////////////////////////////////////////////////////
			System.out.println("LauncherProxy =>");
			System.out.println("\t Recebendo Mensagens ... \n");
			/////////////////////////////////////////////////////////////////////////
			while(this.running) {
				buf = launcherProxyChannel.receiveMessages();
				msg_type = buf.getShort();
				size = buf.getInt();
				switch (msg_type) {
					case Config.NODE_STARTED:
						workerId = Communicator.readString(buf).trim();
						channelDesc = Communicator.readString(buf).trim();
						launcher.nodeStarted(workerId, channelDesc);
					break;
								
					default:
						System.out.println("LauncherProxy =>");
						System.out.println("\t\t LOST MESSAGE! Type: " + msg_type + "\n");
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void sendNewWorker(String nodeId, String nodeChannelDesc, String bossChannelDesc) {
		try {
			this.bossChannelSend = new Communicator();
			this.bossChannelSend.connectServer(bossChannelDesc);

			this.bossChannelSend.sendMsgNewWorker(this.bossChannelSend.getSocket(), nodeId, nodeChannelDesc);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}